package com.kaili.zuul.security;

import com.alibaba.fastjson.JSONObject;
import com.kaili.common.entity.LoginDetail;
import com.kaili.common.response.CommonStatus;
import com.kaili.common.response.ResponseData;
import com.kaili.common.util.LoginDetailUtils;
import com.kaili.zuul.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class SuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    LoginService baseUserService;

    public LoginDetail ld(){
        try {
            LoginDetail loginDetail = LoginDetailUtils.getCurrent();
            Integer employeeId = LoginDetailUtils.getCurrentEmployeeId();
            loginDetail.setCompanyName(baseUserService.getCompanyName(Integer.parseInt(loginDetail.getCode())));
            loginDetail.setSiteId((Integer) baseUserService.getSiteByEmployeeId(employeeId).get("site_id"));
            loginDetail.setSiteCode((String) baseUserService.getSiteByEmployeeId(employeeId).get("site_code"));
            loginDetail.setSiteName((String) baseUserService.getSiteByEmployeeId(employeeId).get("site_name"));
            loginDetail.setName((String)baseUserService.getSiteByEmployeeId(employeeId).get("employee_name"));
            loginDetail.setSiteCode((String)baseUserService.getSiteByEmployeeId(employeeId).get("site_code"));
            baseUserService.updateDict();//系统登陆成功后,根据当前语言环境,设置数据字典名称
            return loginDetail;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        addSecure(response);//解决cookie安全问题

        LoginDetail loginDetail = ld();
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        String s;
        if(loginDetail!=null) {
            s = JSONObject.toJSONString(new ResponseData(JSONObject.toJSON(loginDetail), CommonStatus.OK));
        }else{
            s = JSONObject.toJSONString(new ResponseData(JSONObject.toJSON("帐号异常,无法登陆!"), CommonStatus.CONTINUE));
        }
        out.write(s);
        out.flush();
        out.close();
    }

    private void addSecure(HttpServletResponse response){
        StringBuilder builder = new StringBuilder();
        builder.append("Secure; ");
        builder.append("HttpOnly; ");
        response.setHeader("Set-Cookie", builder.toString());
    }
}
